<?php 
class ModelPhoneNumber extends Model {
	public function addNumber($data) {
		$this->db->query("INSERT INTO phones SET sort_order = '" . (int)$data['sort_order'] . "'");
	}

	public function editNumber($phone_id, $data) {
		$sql = "UPDATE phones SET number = '" . $data['number'] . "', location = '" . $data['location'] . "' WHERE phone_id = '" . (int)$phone_id . "'";
		$this->db->query($sql);
	}

	public function deleteNumber($phone_id) {
		$this->db->query("DELETE FROM phones WHERE phone_id = '" . (int)$phone_id . "'");
	}

	public function getNumber($phone_id) {
		$query = $this->db->query("SELECT * FROM phones WHERE phone_id = '" . (int)$phone_id . "'");

		return $query->row;
	}

	public function getNumbers($data = array()) {
		$sql = "SELECT * FROM phones p";

		$sort_data = array(
				'p.number',
				'p.total_comments',
				'p.total_search'
		);	
		
		echo '<pre>';
		print_r($data);
		echo '</pre>';

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];	
		} else {
			$sql .= " ORDER BY p.number";	
		}	

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}				

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}	

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}	

		$query = $this->db->query($sql);
		echo $sql;
		return $query->rows;
	}

	public function getTotalNumbers() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM phones");

		return $query->row['total'];
	}	
}
?>